﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyLibary;
using FinGu.Testing.Config;
using System.IO;

namespace FinGu.Testing.SoftwareCheck
{
    public class SoftwareCheck : AbsSoftwareCheck
    {
        FinGu.Testing.Config.AbsConfig _config = new FinGu.Testing.Config.Config();
        MyLibary.SqlLibary _sqllib = new MyLibary.SqlLibary();

        const string _SWName = "自动化平台_文件配置工具";
        const string _SWVersion = "P1.1";
        const string _SWDescription = "修改了软件更新部分：优化的代码结构。";
        const string _SWVersionCheckTable = "[mcsdbtrial].[dbo].[Platform_UpdateSoftwave]";
        const string _SWUpdateProgramName = "SoftWaveUpdateList.exe";
        const string _SWUpdateProgramPath = "update\\";
        public string GetSWName()
        {
            return _SWName;
        }
        public string GetSWVersion()
        {
            return _SWVersion;
        }
        public string GetSWDescription()
        {
            return _SWDescription;
        }
        public string GetSWVersionCheckTable()
        {
            return _SWVersionCheckTable;
        }
        public string GetSWUpdateProgramName()
        {
            return _SWUpdateProgramName;
        }
        public string GetSWUpdateProgramPath()
        {
            return _SWUpdateProgramPath;
        }
        private string _UpdateProgramPath = "";
        public void SetUpdateProgramPath(string arg)
        {
            _UpdateProgramPath = arg;
        }
        public string GetUpdateProgramPath()
        {
            return _UpdateProgramPath;
        }

        public override bool CheckSoftWaveVersion(ref string _resultMessage)
        {
            //read config
            string _sSection = "appSettings";
            string _sName = "UpdateSoftwaveConnectionString";
            string _sKey = "";
            string _sValue = "";
            string _info = "";
            string[] _result = null;
            string[] _temp = null;
            int _count = -1;

            if (_config.ReadConfig(_sSection, _sName, ref _sKey, ref _sValue, ref _info))
            {
                _sqllib.SetSqlConnection(_sValue);
                _result = _sValue.Split(';');
                foreach (string arg in _result)
                {
                    _count++;
                    _temp = arg.Split('=');
                    _result[_count] = _temp[1];
                }
            }
            else
            {
                _resultMessage = _info;
                return false;
            }


            //set query conditions
            string checkConditions = "SELECT count(*) as count " +
                "FROM " + GetSWVersionCheckTable() +
                " WHERE [SoftwaveName] = '" + GetSWName() + "'" +
                " AND " +
                "[SoftwaveVersion] = '" + GetSWVersion() + "'";

            //init sql parameters
            _sqllib.SetSqlAddr(_result[0]);
            _sqllib.SetSqlUserID(_result[1]);
            _sqllib.SetSqlPWD(_result[2]);
            _sqllib.SetSqlDB(_result[3]);
            _sqllib.SetSqlTable(GetSWVersionCheckTable());
            _sqllib.SetSqlQueryConditions(checkConditions);

            //connection sql server
            string msg = "";

            if (_sqllib.SqlConnection())
            {
                if (_sqllib.Query(_sqllib.GetSqlQueryConditions(), ref msg))
                {
                    if (msg.Contains("-1"))
                    {
                        _resultMessage = "软件版本: " + GetSWName() + "-"+ GetSWVersion()
                            + "\r\n" + "验证失败！详细：" + msg;
                        return false;
                    }
                    else
                    {
                        _resultMessage = "软件版本: " + GetSWName() + "-" + GetSWVersion();
                        return true;
                    }
                }
                else
                {
                    _resultMessage = "查询数据失败！";
                    return false;
                }
            }
            else
            {
                _resultMessage = "数据库连接失败！";
                return false;
            }
        }
        public override bool Check_SoftWareUpdatListWhetherUpdate(ref string _resultMessage)
        {
            string[,] rs = null;
            string _otherresultMessage;
            string _otherresultMessage2;

            try
            {
                //read config
                string _sSection = "appSettings";
                string _sName = "UpdateSoftwaveConnectionString";
                string _sKey = "";
                string _sValue = "";
                string _info = "";
                string[] _result = null;
                string[] _temp = null;
                int _count = -1;

                if (_config.ReadConfig(_sSection, _sName, ref _sKey, ref _sValue, ref _info))
                {
                    _sqllib.SetSqlConnection(_sValue);
                    _result = _sValue.Split(';');
                    foreach (string arg in _result)
                    {
                        _count++;
                        _temp = arg.Split('=');
                        _result[_count] = _temp[1];
                    }
                }
                else
                {
                    _resultMessage = _info;
                    return false;
                }

                //set query conditions
                string checkConditions = "SELECT [SoftwaveVersion] " +
                    "FROM " + GetSWVersionCheckTable() +
                    " WHERE [SoftwaveName] = '" + GetSWName() + "'";

                //init sql parameters
                _sqllib.SetSqlAddr(_result[0]);
                _sqllib.SetSqlUserID(_result[1]);
                _sqllib.SetSqlPWD(_result[2]);
                _sqllib.SetSqlDB(_result[3]);
                _sqllib.SetSqlTable(GetSWVersionCheckTable());
                _sqllib.SetSqlQueryConditions(checkConditions);

                //connection sql server
                if (_sqllib.SqlConnection() == true)
                {
                    if (_sqllib.GetRecordSet(ref rs, ref _resultMessage) == true)
                    {
                        if (WehterIsExistHighSoftWareVersion(rs, out _otherresultMessage) == true)
                        {
                            //setup updatelist.exe
                            if (SetUpSoftWareUpdateListApp(out _otherresultMessage2) == true)
                            {
                                return true;
                            }
                            else
                            {
                                _resultMessage = _otherresultMessage2;
                                return false;
                            }
                        }
                        else
                        {
                            _resultMessage = _otherresultMessage;
                            return false;
                        }
                    }
                    else
                    {
                        _resultMessage = "get record set is invald.";
                        return false;
                    }
                }
                else
                {
                    _resultMessage = "sql server connection is invald.";
                    return false;
                }

            }
            catch (System.Exception ex)
            {
                _resultMessage = " notify: " + ex.Message;
                return false;
            }
        }

        private bool WehterIsExistHighSoftWareVersion(string[,] arg, out string resultMessage)
        {
            resultMessage = "";

            try
            {
                double[] _swverBag = StrTransformDouble(arg, "P");

                if (FindMaxValueCompareWithSWVersion(_swverBag) == true)
                {
                    resultMessage = GetSWName() + " " + GetSWVersion() + " need update.";
                    return true;
                }
                else
                {
                    resultMessage = GetSWName() + " " + GetSWVersion() + " not need update.";
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                resultMessage = " notify: " + ex.Message;
                return false;
            }
        }
        private bool RecordUpdateProgramPath(out string _resultMessage)
        {
            string _SoftWaveUpdatListPath = "";
            string _CurrentDirectoryPath = "";
            _resultMessage = "";

            try
            {
                _CurrentDirectoryPath = Directory.GetCurrentDirectory();

                Directory.SetCurrentDirectory(_CurrentDirectoryPath + "\\.. ");

                _SoftWaveUpdatListPath = Directory.GetCurrentDirectory() + "\\"
                    + GetSWUpdateProgramPath() + GetSWUpdateProgramName();

                if (Check_SoftWaveUpdatListPathIsExist(_SoftWaveUpdatListPath, out _resultMessage))
                {
                    System.Diagnostics.Process.Start(GetSWUpdateProgramPath() + GetSWUpdateProgramName());

                    SetUpdateProgramPath(Directory.GetCurrentDirectory());

                    _config.WriteConfig("UpdateApplicationPath", GetUpdateProgramPath());

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                _resultMessage = _resultMessage + ex.Message;

                return false;
            }

        }
        private bool LoadUpdateProgramPath(out string _resultMessage)
        {
            string sValue = "";
            string sKey = "";
            string _SoftWaveUpdatListPath = "";
            _resultMessage = "";

            try
            {
                if (_config.ReadConfig("appSettings", "UpdateApplicationPath", ref sKey, ref sValue, ref _resultMessage) == true)
                {
                    Directory.SetCurrentDirectory(sValue);

                    _SoftWaveUpdatListPath = sValue + "\\" + GetSWUpdateProgramPath() + GetSWUpdateProgramName();

                    if (Check_SoftWaveUpdatListPathIsExist(_SoftWaveUpdatListPath, out _resultMessage))
                    {
                        System.Diagnostics.Process.Start(_SoftWaveUpdatListPath);

                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                _resultMessage = _resultMessage + ex.Message;

                return false;
            }
        }
        public bool SetUpSoftWareUpdateListApp(out string _resultMessage)
        {
            _resultMessage = "";

            //如果app.config 中的更新程序路径为空，就去默认地址加载更新程序，加载后记录更新程序的路劲。
            if (GetUpdateProgramPath() == null)
            {
                if (LoadUpdateProgramPath(out _resultMessage))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else//如果app.config 中的更新程序路径不为空，就按照文件记录的地址去加载更新程序。
            {
                if (RecordUpdateProgramPath(out _resultMessage))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

        }
        private bool FindMaxValueCompareWithSWVersion(double[] arg)
        {
            foreach (double indexOfarg in arg)
            {
                if (StrTransformDouble(GetSWVersion(), "P") < indexOfarg)
                {
                    return true;
                }
            }

            return false;
        }
        private double StrTransformDouble(string arg, string killStr)
        {
            return Convert.ToDouble(arg.Replace(killStr, ""));
        }
        private double[] StrTransformDouble(string[,] arg, string killStr)
        {
            double[] _swverBag = new double[arg.GetUpperBound(0) + 1];

            for (int i = 0; i < _swverBag.Length; i++)
            {
                _swverBag[i] = Convert.ToDouble(arg[i, 0].Replace(killStr, ""));
            }

            return _swverBag;
        }
        private bool Check_SoftWaveUpdatListPathIsExist(string path, out string resultMessage)
        {
            resultMessage = "";

            try
            {
                if (File.Exists(path))
                {
                    resultMessage = path + "：is exist.";
                    return true;
                }
                else
                {
                    resultMessage = path + "：is not exist.";
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                resultMessage = path + "：is not exist. notify: " + ex.Message;
                return false;
            }
        }
    }
}
